<?php

namespace app\stationpc\controller;

use app\model\StationOrder as ModelStationOrder;
use app\model\StationBoxOrderLog as ModelStationBoxOrderLog;
use app\model\StationInfo as ModelStationInfo;
use app\model\CashStream as ModelCashStream;
use app\model\StationPassport as ModelStationPassport;

class HomePage extends Member
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 系统首页->上半 \n
     * URI : /stationpc/system.home.page
     * @param :
     *  name      | type   | null| description
     * -----------|--------|-----|-------------
     *  --------- | ------ | 无
     *
     * @return :
     *  name           | type   | description
     * ----------------|--------|-------------
     *  todayOutbound  | int    | 今日出库
     *  todayWarehousing        | int    | 今日入库
     *  todayUnpacking | int    | 今日拆箱
     *  todayPacking   | int    | 今日装箱
     *  balance        | float  | 可提现金额
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function systemHomePage()
    {
        $arr_data = [];
        $str_today_start = date('Y-m-d 00:00:00', time());
        $str_today_end = date('Y-m-d 23:59:59', time());
        $arr_data['todayOutbound'] = ModelStationOrder::getInstance()->toCount(['gmt_create' => ['between', [$str_today_start, $str_today_end]], 'state' => 60]);//今日出库
        $arr_data['todayWarehousing'] = ModelStationOrder::getInstance()->toCount(['gmt_create' => ['between', [$str_today_start, $str_today_end]], 'state' => 40]);//今日入库
        $arr_data['todayUnpacking'] = ModelStationBoxOrderLog::getInstance()->toCount(['gmt_create' => ['between', [$str_today_start, $str_today_end]], 'state' => 15]);//今日拆箱
        $arr_data['todayPacking'] = ModelStationBoxOrderLog::getInstance()->toCount(['gmt_create' => ['between', [$str_today_start, $str_today_end]], 'state' => 10]);//今日装箱
        $arr_data['balance'] = ModelStationInfo::getInstance()->toSum(['id'=>$this->station_id], 'balance');//可提现金额
        if($arr_data['balance'] == null)
        {
            $arr_data['balance'] = 0;
        }
        _returnData(['list' => $arr_data]);
    }

    /**
     * 入库统计 \n
     * URI : /stationpc/warehousing.statistics
     * @param :
     *  name      | type   | null| description
     * -----------|--------|-----|-------------
     *  gmtStart  | string | 必填 | 开始时间（gmtStart = '2018-04-01 00:00:00'  ;//)
     *  gmtEnd    | string | 必填 | 结束时间（gmtStart = '2018-04-30 23:59:59'  ;//)
     *
     * @return :
     *  name           | type   | description
     * ----------------|--------|-------------
     *  data           | float  | 入库数量
     *  arrNum         | array  | 每天的数量（筛选的曲线图）
     *  arrTime        | array  | 每天的日期（筛选的曲线图）
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function warehousingStatistics()
    {
        $gmt_start = $this->_getContentParams('gmtStart');
        $gmt_end = $this->_getContentParams('gmtEnd');
        $arr_data = $this->orderNum($gmt_start, $gmt_end) ? $this->orderNum($gmt_start, $gmt_end) : 0;
        $str_day = (strtotime($gmt_end) - strtotime($gmt_start)) / 86400;
        $numImg = $this->orderNumImg(strtotime($gmt_start), $str_day);
        _returnData(['data' => $arr_data, 'arrNum' => $numImg['arr_num'], 'arrTime' => $numImg['arr_time']]);
    }

    /**
     * @param $gmtStart
     * @param $gmtEnd
     * @return int
     */
    public function orderNum($gmtStart, $gmtEnd)
    {
        _toCompare(empty($gmtStart), '===', true, 30001);
        _toCompare(empty($gmtEnd), '===', true, 30002);
        _toCompare($gmtStart, '>', $gmtEnd, 30003);
        return ModelStationOrder::getInstance()->toCount(['gmt_create' => ['between', [$gmtStart, $gmtEnd], 'state' => 40]]);
    }

    /**
     * @param $str_sunday
     * @param $str_day
     * @return array
     */
    public function orderNumImg($str_sunday, $str_day)
    {
        $arr_data = [];
        $arr_num = [];
        $arr_time = [];
        for ($i = 0; $i < $str_day; $i++) {
            $arr_num[$i] = $this->orderNum(date('Y-m-d 00:00:00', $str_sunday), date('Y-m-d 23:59:59', $str_sunday));
            $arr_num[$i] = $arr_num[$i] ? $arr_num[$i] : 0;
            $arr_time[$i] = date('m-d', $str_sunday);
            $str_sunday = ($str_sunday + 86400);
        }
        $arr_data['arr_num'] = $arr_num;
        $arr_data['arr_time'] = $arr_time;
        return $arr_data;
    }

    /**
     * 收入统计 \n
     * URI : /stationpc/income.statistical
     * @param :
     *  name      | type   | null| description
     * -----------|--------|-----|-------------
     *  gmtStart  | string | 必填 | 开始时间（gmtStart = '2018-04-01 00:00:00'  ;//)
     *  gmtEnd    | string | 必填 | 结束时间（gmtStart = '2018-04-30 23:59:59'  ;//)
     *
     * @return :
     *  name           | type   | description
     * ----------------|--------|-------------
     *  data           | float  | 收入总额
     *  arrNum         | array  | 每天的收入总额（筛选的曲线图）
     *  gmtEnd         | array  | 每天的日期（筛选的曲线图）
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function incomeStatistical()
    {
        $gmt_start = $this->_getContentParams('gmtStart');
        $gmt_end = $this->_getContentParams('gmtEnd');
        $arr_data = $this->moneyNum($gmt_start, $gmt_end);
        $str_day = (strtotime($gmt_end) - strtotime($gmt_start)) / 86400;
        $numImg = $this->moneyNumImg(strtotime($gmt_start), $str_day);
        _returnData(['data' => $arr_data, 'arrNum' => $numImg['arr_num'], 'arrTime' => $numImg['arr_time']]);
    }

    /**
     * @param $gmtStart
     * @param $gmtEnd
     * @return int
     */
    public function moneyNum($gmtStart, $gmtEnd)
    {
        _toCompare(empty($gmtStart), '===', true, 21001);
        _toCompare(empty($gmtEnd), '===', true, 21002);
        _toCompare($gmtStart, '>', $gmtEnd, 21003);
        $str_money = ModelCashStream::getInstance()->toSum(['gmt_create' => ['between', [$gmtStart, $gmtEnd]], 'map_type' => 3, 'is_income' => 0], 'money');
        if ($str_money == null) {
            $str_money = 0;
        }
        return $str_money;
    }

    /**
     * @param $str_sunday
     * @param $str_day
     * @return array
     */
    public function moneyNumImg($str_sunday, $str_day)
    {
        $arr_data = [];
        $arr_num = [];
        $arr_time = [];
        for ($i = 0; $i < $str_day; $i++) {
            $arr_num[] = $this->moneyNum(date('Y-m-d 00:00:00', $str_sunday), date('Y-m-d 23:59:59', $str_sunday));
            $arr_num[$i] = $arr_num[$i] ? $arr_num[$i] : 0;
            $arr_time[] = date('m-d', $str_sunday);
            $str_sunday = ($str_sunday + 86400);
        }
        $arr_data['arr_num'] = $arr_num;
        $arr_data['arr_time'] = $arr_time;
        return $arr_data;
    }

    /**
     * 首页->账户设置->详情信息 \n
     * URI : /stationpc/member.details
     * @param :
     *  name          | type   | null | description
     * ---------------|--------|------|-------------
     *  passport      | string | 必填  | 凭证
     *
     * @return :
     *  name          | type    | description
     * ---------------|---------|-------------
     *  adminName     | string  | 昵称
     *  adminEmial    | string  | 邮箱
     *  headPortrait  | string  | 头像
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function memberDetails()
    {
        $arr_data = ModelStationInfo::getInstance()->toFind(['id' => $this->station_id], 'login_account AS loginAccount,emial,head_portrait AS headPortrait');
        _returnData($arr_data);
    }

    /**
     * 首页->账户设置->修改密码 \n
     * URI : /stationpc/member.modify.pwd
     * @param :
     *  name          |  type  | null | description
     * ---------------|--------|------|-------------
     *  passport      | string | 必填  | 凭证
     *  headPortrait  | string | 选填  | 头像
     *  password      | string | 必填  | 旧密码
     *  newPassword   | string | 必填  | 新密码
     *
     * @return :
     *  name        |  type  | description
     * -------------|--------|-------------
     *  ----------- | ------ | 无
     *
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function memberModifyPassword()
    {

        $str_head_portrait = $this->_getContentParams('headPortrait'); // 头像
        $str_password = $this->_getContentParams('password'); // 旧密码
        _toValidate('login_pwd', $str_password, 19013);
        $arr_pwd_info = ModelStationInfo::getInstance()->toFind(['id' => $this->station_id], 'password,pwd_key');
        _toCompare(passwordEncryption($str_password, $arr_pwd_info['pwd_key']), '!=', $arr_pwd_info['password'], 19012);
        $str_new_password = $this->_getContentParams('newPassword'); //新密码
        _toValidate('login_pwd', $str_new_password, 19025);
        ModelStationInfo::getInstance()->toUpdate(['id' => $this->station_id], ['password' => passwordEncryption($str_new_password, $arr_pwd_info['pwd_key']), 'head_portrait' => $str_head_portrait]);
        _returnData();
    }

    /**
     * 首页->系统信息 \n
     * URI : /stationpc/stem.information
     * @param :
     *  name       | type   | null | description
     * ------------|--------|------|-------------
     *  ---------- | ------ | 无
     *
     * @return :
     *  name       | type   | description
     * ------------|--------|-------------
     *  list       | array  | 列表
     *
     * list:
     *  name                | type   | description
     * ---------------------|--------|-------------
     *  systemServer        | string | 服务器操作系统
     *  webServer           | string | Web 服务器
     *  phpVersion          | string | PHP 版本
     *  sqlVersion          | string | MySQL 版本
     *  safeMode            | string | 安全模式
     *  safeGid             | string | 安全模式GID
     *  socketSupport       | string | socket支持
     *  timeZone            | string | 时区设置
     *  gdVersion           | string | GD 版本
     *  zlibSupport         | string | Zlib 支持
     *  ipLibraryVersion    | string | IP 库版本
     *  fileUpload          | string | 文件上传的最大大小:
     *  programVersion      | string | v2.2.2 RELEASE 20170629
     *  installationDate    | string | 安装日期
     *  codeUtf             | string | 编码
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function stemInformation()
    {
        $arr_data = [];
        $arr_data['systemServer'] = 'Linux (114.55.34.251)';  //服务器操作系统
        $arr_data['webServer'] = 'nginx/1.10.2';           //Web 服务器
        $arr_data['phpVersion'] = '5.6.30';                 //PHP 版本
        $arr_data['sqlVersion'] = '5.5.56';                 //MySQL 版本
        $arr_data['safeMode'] = '否';                     //安全模式
        $arr_data['safeGid'] = '否';                     //安全模式GID
        $arr_data['socketSupport'] = '是';                     //socket支持
        $arr_data['timeZone'] = 'Asia/Shanghai';          //时区设置
        $arr_data['gdVersion'] = 'GD2 ( JPEG GIF PNG)';    //GD 版本
        $arr_data['zlibSupport'] = '是';                     //Zlib 支持
        $arr_data['ipLibraryVersion'] = '20071024';               //IP 库版本
        $arr_data['fileUpload'] = '40M';                    //文件上传的最大大小:
        $arr_data['programVersion'] = 'v2.2.2 RELEASE 20170629';//v2.2.2 RELEASE 20170629
        $arr_data['installationDate'] = '2017-12-28';             //安装日期
        $arr_data['codeUtf'] = 'UTF-8';                  //编码
        _returnData(['list' => $arr_data]);
    }

    /**
     * 首页->登录日志列表 \n
     * URI : /stationpc/login.log.list
     * @param :
     *  name     | type   | null | description
     * ----------|--------|------|-------------
     *  page     | int    | 必填  | 页码
     *  listRows | int    | 必填  | 一页的条数
     *
     * @return
     *  name       | type   | description
     * ------------|--------|-------------
     *  totalPages | string | 总页数
     *  list       | array  | 列表
     *
     * list:
     *  name        | type   | description
     * -------------|--------|-------------
     *  platform    | string | 登录工具
     *  ip          | string | ip
     *  gmtCreate   | string | 登录时间
     *  province    | string | 省
     *  city        | string | 市
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function loginLogList()
    {

        $int_now_page = $this->_getContentParams('page'); // 当前页码
        _toValidate('id', $int_now_page, 10005);

        $int_list_rows = $this->_getContentParams('listRows'); // 一页的条数
        _toValidate('id', $int_list_rows, 10006);
        $arr_where = [];
        $int_total_rows = ModelStationPassport::getInstance()->toCount($arr_where);
        $int_total_pages = (int)ceil($int_total_rows / $int_list_rows);//总页数
        _toCompare(($int_now_page > $int_total_pages && $int_total_pages > 0), '===', true, 10007);
        $int_first_row = $int_list_rows * ($int_now_page - 1);//从第几条开始查询
        $str_field = 'platform,ip,gmt_create AS gmtCreate';
        $arr_list = ModelStationPassport::getInstance()->toSelect($arr_where, $str_field, $int_first_row, $int_list_rows, 'gmt_create desc');
        foreach ($arr_list as &$value) {
            $arr_address = $this->GetIpLookup($value['ip']);
            $value['province'] = $arr_address['province'];
            $value['city'] = $arr_address['city'];
        }
        _returnData(['totalPages' => $int_total_pages, 'list' => $arr_list]);
    }

    /**
     * 头像 \n
     * URI : /stationpc/account.information
     * @param :
     *  name         | type   | null | description
     * --------------|--------|------|-------------
     *  passport     | string | 必填  | 凭证
     *
     * @return
     *  name         | type   | description
     * --------------|--------|-------------
     *  loginAccount | string | 登陆账号
     *  headPortrait | string | 头像
     *  name         | string | 站点名称
     *  gmt          | string | 最新登录时间
     *  ip           | string | ip
     *  province     | string | 省
     *  city         | string | 市
     *  gmtGheLast   | string | 最后一次登录时间
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function accountInformation()
    {
        $arr_admin_find = ModelStationInfo::getInstance()->toFind(['id' => $this->station_id], 'login_account AS loginAccount,head_portrait AS headPortrait,name');
        $arr_data['loginAccount'] = $arr_admin_find['loginAccount'];
        $arr_data['headPortrait'] = $arr_admin_find['headPortrait'];
        $arr_data['name'] = $arr_admin_find['name'];
        $arr_data['gmt'] = $this->_now;
        $arr_data['ip'] = $this->getIP();
        $arr_address = $this->GetIpLookup($arr_data['ip']);
        $arr_data['province'] = $arr_address['province'];
        $arr_data['city'] = $arr_address['city'];
        $arr_data['gmtGheLast'] = ModelStationPassport::getInstance()->toMax(['passport' =>  $this->_getContentParams('passport')], 'gmt_create');
        _returnData($arr_data);
    }


}
